//  Copyright 2011 Google Inc. All Rights Reserved.
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#import('dart:io');
#import('isolet.dart');

String template(path, method, headers, queryParams, [body]) => """
  <!doctype html>
  <html>
    <form action="/echo" method="POST">
      <textarea name="test"></textarea>
      <input type="submit"/>
    </form>
    <table>
      <tr><th>path</th><td>$path</td></tr>
      <tr><th>method</th><td>$method</td></tr>
      <tr><th>headers</th><td>$headers</td></tr>
      <tr><th>queryParameters</th><td>$queryParams</td></tr>
      <tr><th>body</th><td>$body</td></tr>
    </table>
  </html>
""";

void main() {
  HttpServer server = new IsoletServer();
  server.defaultRequestHandler = (HttpRequest req, HttpResponse res) {
    if (req.method == 'GET') {
      _render(req, res);
      res.outputStream.close();
    } else if (req.method == 'POST') {
      StringInputStream sis = new StringInputStream(req.inputStream);
      sis.onData = () {
        print("onData");
        String content = sis.read();
        print("content: $content");
        _render(req, res, content);
      };
      sis.onClosed = () {
        print("closed");
        res.outputStream.close();      
      };
      sis.onError = (e) {
        print("error: $e");
        res.outputStream.close();      
      };
    };
  };
}

void _render(HttpRequest req, HttpResponse res, [String body]) {
  res.headers.set(HttpHeaders.CONTENT_TYPE, "text/html");
  
  res.outputStream.writeString(template(
    req.path,
    req.method,
    req.headers,
    req.queryParameters,
    body));
}